package com.velvetantler.weather.view.mine

import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.velvetantler.weather.WeatherApplication
import com.velvetantler.weather.base.BaseBindingActivity
import com.velvetantler.weather.constants.Constants
import com.velvetantler.weather.databinding.ActChangeAvatarBinding
import com.velvetantler.weather.utils.PreferenceUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.io.FileOutputStream

class UpdateProfileActivity : BaseBindingActivity<ActChangeAvatarBinding>() {

//    private val REQUEST_CODE_GALLERY = 100
//    private val REQUEST_CODE_CAMERA = 200

    private lateinit var galleryLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 初始化头像显示
        initView()
    }

    override fun initBinding(layoutInflater: LayoutInflater): ActChangeAvatarBinding {
        return ActChangeAvatarBinding.inflate(layoutInflater)
    }

    private fun initView() {
        // 初始化点击事件
        initOnClickListener()

        // 初始化头像显示
        Glide.with(this).load(WeatherApplication.getGlobalContext()!!.userInfo?.avatar ?: "")
            .into(binding.ivAvatar)

        // 初始化相册选取回调
        initOpenGalleryCallback()
    }

    private fun initOnClickListener() {
        // 初始化返回按钮
        binding.ivBack.setOnClickListener {
            finish()
        }
        // 初始化头像点击后弹框
        binding.ivAvatar.setOnClickListener {
            showChooseDialog()
        }
        binding.ivEditAvatar.setOnClickListener {
            showChooseDialog()
        }
    }

    private fun showChooseDialog() {
        AlertDialog.Builder(this)
            .setTitle("选择头像")
            .setItems(arrayOf("拍照", "从相册选择", "取消")) { dialog, which ->
                when (which) {
                    0 -> {
                        // 拍照
                    }

                    1 -> {
                        // 相册
                        openGallery()
                    }

                    2 -> {
                        // 取消
                        dialog.dismiss()
                    }
                }
            }
            .create()
            .show()
    }

    private fun initOpenGalleryCallback() {
        galleryLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                val uri = data?.data
                Log.i("UpdateProfileActivity", "initOpenGalleryCallback: $uri")
                binding.ivAvatar.setImageURI(uri)
                // 上传图片到服务器
                uploadAvatar(uri)
            }
        }
    }

    private fun openGallery() {
        try {
            // 打开相册
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            // 拉起相册，并注册结果回调
            galleryLauncher.launch(intent)
//        startActivityForResult(intent, REQUEST_CODE_GALLERY)
        } catch (e: Exception) {
            Log.e("UpdateProfileActivity", "openGallery: ${e.message}")
        }
    }

    /**
     * 上传头像
     */
    private fun uploadAvatar(uri: Uri?) {
        lifecycleScope.launch {
            try {
                val response = withContext(Dispatchers.IO) {
                    // 1. 把uri转换成文件对象
                    val file = uri?.let {
                        var tempFile = File.createTempFile("tempAvatar", ".jpg", cacheDir)
                        var inputStream =
                            this@UpdateProfileActivity.contentResolver.openInputStream(it)
                        val outputStream = FileOutputStream(tempFile)
                        inputStream?.copyTo(outputStream)
                        outputStream.flush()
                        tempFile
                    }
                    // 2. 创建Multipart请求体
                    val requestBody = MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart(
                            "avatar",
                            file?.name,
                            file!!.asRequestBody("image/*".toMediaTypeOrNull())
                        )
                        .build()
                    // 3. 构建请求
                    val token = PreferenceUtil.getInstance(this@UpdateProfileActivity)
                        .getValue(Constants.TOKEN_PREF_KEY)
                    val request = Request.Builder()
                        .url(Constants.BASE_URL + "upload-avatar")
                        .post(requestBody)
                        .addHeader("Authorization", "Bearer $token")
                        .build()
                    // 4.发送请求
                    val httpClient = OkHttpClient()
                    httpClient.newCall(request).execute()
                }
                if (response.code == 200) {
                    Toast.makeText(this@UpdateProfileActivity, "上传成功", Toast.LENGTH_SHORT)
                        .show()
                }
            } catch (e: Exception) {
                Log.e("UpdateProfileActivity", "uploadAvatar fail: ${e.message}")
            }
        }
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        when (requestCode) {
//            REQUEST_CODE_GALLERY -> {
//                if (resultCode == RESULT_OK) {
//                    val uri = data?.data
//                    binding.ivAvatar.setImageURI(uri)
//                }
//            }
//
//            REQUEST_CODE_CAMERA -> {
//                if (resultCode == RESULT_OK) {
//                    val uri = data?.data
//                    binding.ivAvatar.setImageURI(uri)
//                }
//            }
//        }
//    }
}